<template>
  <div class="payment-settings">
    <t-form :data="formData" :rules="rules" :label-width="120" @submit="handleSubmit">
      <!-- 微信支付设置 -->
      <t-divider>微信支付设置</t-divider>
      
      <t-form-item label="启用微信支付">
        <t-switch v-model="formData.wechatEnabled" />
      </t-form-item>
      
      <template v-if="formData.wechatEnabled">
        <t-form-item label="商户ID" name="wechatMchId">
          <t-input v-model="formData.wechatMchId" placeholder="请输入微信支付商户ID" />
        </t-form-item>
        
        <t-form-item label="应用ID" name="wechatAppId">
          <t-input v-model="formData.wechatAppId" placeholder="请输入微信支付应用ID" />
        </t-form-item>
        
        <t-form-item label="API密钥" name="wechatApiKey">
          <t-input
            v-model="formData.wechatApiKey"
            type="password"
            placeholder="请输入微信支付API密钥"
            :password-visible="passwordVisible.wechat"
            @password-visible-change="(visible: boolean) => passwordVisible.wechat = visible"
          />
        </t-form-item>
        
        <t-form-item label="证书文件" name="wechatCertFile">
          <t-upload
            v-model="formData.wechatCertFile"
            theme="file"
            action="/api/upload/cert"
            accept=".p12,.pem,.crt,.key"
            :headers="{ Authorization: `Bearer ${token}` }"
            :limit="1"
            :sizeLimit="{ size: 2, unit: 'MB' }"
            @success="handleCertUploadSuccess('wechat')"
          />
        </t-form-item>
        
        <t-form-item label="通知URL">
          <t-input disabled :value="notifyUrls.wechat" />
          <t-button theme="default" variant="text" @click="copyUrl('wechat')">
            <template #icon><t-icon name="copy" /></template>
            复制
          </t-button>
        </t-form-item>
      </template>
      
      <!-- 支付宝设置 -->
      <t-divider>支付宝设置</t-divider>
      
      <t-form-item label="启用支付宝">
        <t-switch v-model="formData.alipayEnabled" />
      </t-form-item>
      
      <template v-if="formData.alipayEnabled">
        <t-form-item label="应用ID" name="alipayAppId">
          <t-input v-model="formData.alipayAppId" placeholder="请输入支付宝应用ID" />
        </t-form-item>
        
        <t-form-item label="应用私钥" name="alipayPrivateKey">
          <t-textarea
            v-model="formData.alipayPrivateKey"
            placeholder="请输入支付宝应用私钥"
            :autosize="{ minRows: 3, maxRows: 6 }"
          />
        </t-form-item>
        
        <t-form-item label="支付宝公钥" name="alipayPublicKey">
          <t-textarea
            v-model="formData.alipayPublicKey"
            placeholder="请输入支付宝公钥"
            :autosize="{ minRows: 3, maxRows: 6 }"
          />
        </t-form-item>
        
        <t-form-item label="通知URL">
          <t-input disabled :value="notifyUrls.alipay" />
          <t-button theme="default" variant="text" @click="copyUrl('alipay')">
            <template #icon><t-icon name="copy" /></template>
            复制
          </t-button>
        </t-form-item>
      </template>
      
      <!-- 银联支付设置 -->
      <t-divider>银联支付设置</t-divider>
      
      <t-form-item label="启用银联支付">
        <t-switch v-model="formData.unionpayEnabled" />
      </t-form-item>
      
      <template v-if="formData.unionpayEnabled">
        <t-form-item label="商户ID" name="unionpayMchId">
          <t-input v-model="formData.unionpayMchId" placeholder="请输入银联支付商户ID" />
        </t-form-item>
        
        <t-form-item label="证书文件" name="unionpayCertFile">
          <t-upload
            v-model="formData.unionpayCertFile"
            theme="file"
            action="/api/upload/cert"
            accept=".p12,.pem,.crt,.key"
            :headers="{ Authorization: `Bearer ${token}` }"
            :limit="1"
            :sizeLimit="{ size: 2, unit: 'MB' }"
            @success="handleCertUploadSuccess('unionpay')"
          />
        </t-form-item>
        
        <t-form-item label="通知URL">
          <t-input disabled :value="notifyUrls.unionpay" />
          <t-button theme="default" variant="text" @click="copyUrl('unionpay')">
            <template #icon><t-icon name="copy" /></template>
            复制
          </t-button>
        </t-form-item>
      </template>
      
      <!-- 订单设置 -->
      <t-divider>订单设置</t-divider>
      
      <t-form-item label="订单超时时间(分钟)" name="orderTimeout">
        <t-input-number v-model="formData.orderTimeout" :min="1" :max="1440" />
      </t-form-item>
      
      <t-form-item label="自动确认收货(天)" name="autoConfirmDays">
        <t-input-number v-model="formData.autoConfirmDays" :min="1" :max="30" />
      </t-form-item>
      
      <t-form-item label="允许退款期限(天)" name="refundDays">
        <t-input-number v-model="formData.refundDays" :min="0" :max="30" />
        <div class="form-item-help">设置为0表示不允许退款</div>
      </t-form-item>
      
      <t-form-item>
        <t-space>
          <t-button theme="primary" type="submit" :loading="submitLoading">保存设置</t-button>
          <t-button theme="default" variant="base" @click="resetForm">重置</t-button>
        </t-space>
      </t-form-item>
    </t-form>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { MessagePlugin } from 'tdesign-vue-next'

// 假设从某处获取token
const token = 'example_token'

// 通知URL
interface NotifyUrls {
  wechat: string;
  alipay: string;
  unionpay: string;
  [key: string]: string;
}

const notifyUrls = reactive<NotifyUrls>({
  wechat: 'https://api.example.com/payment/notify/wechat',
  alipay: 'https://api.example.com/payment/notify/alipay',
  unionpay: 'https://api.example.com/payment/notify/unionpay'
})

// 密码可见状态
const passwordVisible = reactive({
  wechat: false
})

// 表单数据
const formData = reactive({
  // 微信支付
  wechatEnabled: false,
  wechatMchId: '',
  wechatAppId: '',
  wechatApiKey: '',
  wechatCertFile: [],
  
  // 支付宝
  alipayEnabled: false,
  alipayAppId: '',
  alipayPrivateKey: '',
  alipayPublicKey: '',
  
  // 银联支付
  unionpayEnabled: false,
  unionpayMchId: '',
  unionpayCertFile: [],
  
  // 订单设置
  orderTimeout: 30,
  autoConfirmDays: 7,
  refundDays: 7
})

// 表单验证规则
const rules = {
  // 微信支付
  wechatMchId: [{ required: true, message: '请输入微信支付商户ID', type: 'error', trigger: 'blur' }],
  wechatAppId: [{ required: true, message: '请输入微信支付应用ID', type: 'error', trigger: 'blur' }],
  wechatApiKey: [{ required: true, message: '请输入微信支付API密钥', type: 'error', trigger: 'blur' }],
  
  // 支付宝
  alipayAppId: [{ required: true, message: '请输入支付宝应用ID', type: 'error', trigger: 'blur' }],
  alipayPrivateKey: [{ required: true, message: '请输入支付宝应用私钥', type: 'error', trigger: 'blur' }],
  alipayPublicKey: [{ required: true, message: '请输入支付宝公钥', type: 'error', trigger: 'blur' }],
  
  // 银联支付
  unionpayMchId: [{ required: true, message: '请输入银联支付商户ID', type: 'error', trigger: 'blur' }]
}

// 提交状态
const submitLoading = ref(false)

// 获取支付设置
const fetchSettings = async () => {
  try {
    // 这里应该从API获取数据
    // const { data } = await getPaymentSettings()
    
    // 模拟数据
    const data = {
      wechatEnabled: true,
      wechatMchId: '1234567890',
      wechatAppId: 'wx1234567890',
      wechatApiKey: '******',
      
      alipayEnabled: true,
      alipayAppId: '2021000000000000',
      alipayPrivateKey: '******',
      alipayPublicKey: '******',
      
      unionpayEnabled: false,
      unionpayMchId: '',
      
      orderTimeout: 30,
      autoConfirmDays: 7,
      refundDays: 7
    }
    
    // 填充表单数据
    if (data) {
      Object.assign(formData, data)
    }
  } catch (error) {
    console.error('获取支付设置失败', error)
    MessagePlugin.error('获取支付设置失败')
  }
}

// 提交表单
const handleSubmit = async () => {
  submitLoading.value = true
  try {
    // 这里应该调用API保存数据
    // await updatePaymentSettings(formData)
    
    // 模拟API调用延迟
    await new Promise(resolve => setTimeout(resolve, 1000))
    
    MessagePlugin.success('保存成功')
  } catch (error) {
    console.error('保存支付设置失败', error)
    MessagePlugin.error('保存支付设置失败')
  } finally {
    submitLoading.value = false
  }
}

// 重置表单
const resetForm = () => {
  fetchSettings()
}

// 证书上传成功回调
const handleCertUploadSuccess = (type: 'wechat' | 'unionpay') => {
  MessagePlugin.success(`${type === 'wechat' ? '微信' : '银联'}证书上传成功`)
}

// 复制URL
const copyUrl = (type: 'wechat' | 'alipay' | 'unionpay') => {
  navigator.clipboard.writeText(notifyUrls[type])
    .then(() => {
      MessagePlugin.success('复制成功')
    })
    .catch(() => {
      MessagePlugin.error('复制失败')
    })
}

// 初始化
onMounted(() => {
  fetchSettings()
})
</script>

<style scoped>
.payment-settings {
  padding: 20px 0;
}

.form-item-help {
  font-size: 12px;
  color: rgba(0, 0, 0, 0.4);
  margin-top: 4px;
}
</style> 